package com.demo.config;

import com.demo.contants.RabbitContent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class RabbitConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback {


    @Autowired
    private RabbitTemplate rabbitTemplate;


    @PostConstruct
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if(ack)
            log.info("消息成功发送到交换机");
        else
            log.info("消息发送到交换机失败");
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        log.info("消息从交换机发送到消息队列失败");
    }

    // 配置死性队列
    @Bean
    public DirectExchange dlxExchange(){
        return new DirectExchange(RabbitContent.DLX_EXCHANGE_NAME, true, false);
    }

    @Bean
    public Queue dlxQueue(){
        return new Queue(RabbitContent.DLX_QUEUE_NAME, true, false, false);
    }

    @Bean
    public Binding dlxBindingDirect(){
        return BindingBuilder.bind(dlxQueue()).to(dlxExchange()).with(RabbitContent.DLX_ROUTING_KEY_NAME);
    }

    //配置普通队列
    @Bean
    public DirectExchange payExchange(){
        return new DirectExchange(RabbitContent.PAY_EXCHANGE_NAME, true, false);
    }

    @Bean
    public Queue payQueue(){
        Map<String, Object> map = new HashMap<>();
        map.put("x-message-ttl", 100000); //设置消息过期时间
        map.put("x-dead-letter-exchange", RabbitContent.DLX_EXCHANGE_NAME); //设置死性交换机
        map.put("x-dead-letter-routing-key", RabbitContent.DLX_ROUTING_KEY_NAME); //设置死性routingKey
        return new Queue(RabbitContent.PAY_QUEUE_NAME, true, false, false, map);
    }

    @Bean
    public Binding payBindingDirect(){
        return BindingBuilder.bind(payQueue()).to(payExchange()).with(RabbitContent.PAY_ROUTING_KEY);
    }
}
